﻿module Sustainalytics.Company {

    import Common = Sustainalytics.Common;
    import Pager = Sustainalytics.Pager;

    // Company List controller
    export class CompanyListController {
        // order by
        public orderByCol: string;
        public orderByAsc: boolean;

        // list of Companys
        public companyList: CorporateDataDto[];
        // total number of Companys
        public companyCount: number;
        //private accountId: string;
        //private userId: string;
        public hasCompanyPermision: boolean;
        public companySearchText: string;
        public tempSearch: string;

        private scopeDestroyed: boolean;

        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private CompanyService: CompanyService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects,
            private LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService,
            private $modal: Common.IModal) {

            var ctx = this;

            $scope['companyList'] = ctx;

            ctx.scopeDestroyed = false;
            ctx.orderByCol = "CompanyNameLowerCase";
            ctx.orderByAsc = true;

          ctx.handlePagerChanged();
            ctx.handleScopeDestroyed();
        }

        // when scope is destroyed keep a flag to prevent some operations
        // eg: bootstrap UI tab delete each tab and select the next that causing 
        // in current case to trigger multiple requests while tabs are being disposed 
        // which is unnecessary
        private handleScopeDestroyed() {
            var ctx = this;

            // when scope is destroyed
            ctx.$scope.$on('$destroy', function () {
                ctx.scopeDestroyed = true;
            });
        }

        // search for Companys when pager changes
        private handlePagerChanged() {
            var ctx = this;

            ctx.$scope.$on('pagerChanged', function (ev, pager: Pager.PagerController) {
                ctx.searchCompany();
            });
        }

        public setOrderByCol(col: string) {
            var ctx = this;

            if (ctx.orderByCol === col) {
                ctx.orderByAsc = !ctx.orderByAsc;
            }
            else {
                if (col === "HasEsgResearch" || col === "HasGovernanceResearch" || col === "HasControversyResearch" || col === "HasGccsResearch" || col === "PIResearchState") {
                    ctx.orderByCol = col;
                    ctx.orderByAsc = false;
                } else {
                    ctx.orderByCol = col;
                    ctx.orderByAsc = true;
                }
            }
            ctx.searchCompany();
        }

        public searchButtonClick() {
            var ctx = this;
            ctx.companySearchText = ctx.tempSearch;

            // go to page 1
            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager)
                return;

            pager.goTo(1);
        }

        // search list of Companys
        public searchCompany(): ng.IPromise<{}> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;


            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager) {
                var def = ctx.$q.defer();
                def.reject();
                return def.promise;
            }

            var skip = pager.skipCount();
            var take = pager.takeCount();

            // get Company items
            var promiseGet: ng.IPromise<CorporateDataDto[]> = ctx.CompanyService.getCompanies(ctx.companySearchText, skip, take, ctx.orderByCol, ctx.orderByAsc, true);

            var companyListTemp: CorporateDataDto[];

            //on success list Companys
            promiseGet.then(function (lst) {
                companyListTemp = lst;
            });

            //get Companys count
            var promiseCount: ng.IPromise<number> = ctx.CompanyService.getCompaniesCount(ctx.companySearchText, true);

            var CompanyCountTemp: number;

            //on success 
            promiseCount.then(function (count) {
                CompanyCountTemp = count;
            });

            // after get and count are resolved set controller properties
            var promiseAll = ctx.$q.all([promiseGet, promiseCount]);

            promiseAll
                .then(function () {
                    ctx.companyList = companyListTemp;
                    ctx.companyCount = CompanyCountTemp['companyCount'];
                    pager.setTotalItemsCount(CompanyCountTemp['companyCount']);
                })
            ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });

            return promiseAll;
        }
    }

    // register controller with News Angular module
    angular.module('Sustainalytics.Company').controller('CompanyListController', function ($rootScope: ng.IScope, $scope: ng.IScope, $q: ng.IQService, $location: ng.ILocationService, CompanyService, notificationFactory: Common.INotificationFactory, staticObjects: Common.IStaticObjects, LongRunningTaskManagerService, $modal: Common.IModal) {
        var ctrl = new Sustainalytics.Company.CompanyListController($rootScope, $scope, $q, $location, CompanyService, notificationFactory, staticObjects, LongRunningTaskManagerService, $modal);
        return ctrl;
    });
}  